/* 
 * @Author: 21克的爱情
 * @Date: 2020-09-04 15:25:28
 * @Email: raohong07@163.com
 * @LastEditors: 21克的爱情
 * @LastEditTime: 2020-10-03 23:02:51
 * @Description: http://dy.ataoju.com/svip/api.php?url=http%3A%2F%2Fv.qq.com%2Fx%2Fcover%2Fmzc002003qfojfs%2Fo0034ec5q14.html&cb=jQuery182024822996053963864_1601363502922&_=1601363503113
 */
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:ki5k_video/api/Api.dart';
import 'package:ki5k_video/models/origin.dart';
import 'package:ki5k_video/models/video_attr.dart';
import 'package:ki5k_video/models/video_list.dart';
import 'package:awsome_video_player/awsome_video_player.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xml/xml.dart';

import '../home/video/video_play_page.dart';
import '../../provide/application_provide.dart';


class VideoDetailApiPage extends StatefulWidget {
  final String id;
  VideoDetailApiPage(this.id, {Key key}) : super(key: key);

  @override
  _VideoDetailApiPageState createState() => _VideoDetailApiPageState();
}

class _VideoDetailApiPageState extends State<VideoDetailApiPage> {
  String title='';
  List<String> origin=[];
  List<Origin> originUrl=[];

  String _selectType;

  List<VideoAttr> formVideoData=[];
  VideoDetail videoDetail;

  VideoAttr currentData;

  List<VideoAttr> detailData = [];

  @override
  void initState() { 
    super.initState();
    
    if(!mounted) return;
    print(context.read<ApplicationStatus>().isFullscreen);
    formatData();
  }

  void formatData() async {
    await Api().getApi2Video({
      'url': '${widget.id}', //'https://www.iqiyi.com/v_2g5a5i86730.html''',
      'cb': '',
      '_':'',
    }).then((value) async {
      if( value != null && value.isNotEmpty ){
        if (value['info'] != null && value['info'].isNotEmpty) {
          value['info'].forEach((video){
            List videoData = video['video'].map((item){
              List<String> videoList = item.split('\$');
              return {
                'title': videoList[0],
                'url': videoList.length >= 2 ? videoList[1] : '',
                'type': video['flag'],
              };
            }).toList();
            formVideoData.addAll(getVideoAttrList(videoData));
          });
          for(int i = 0; i < value['info'].length; i++){
            Map video = value['info'][i];
            detailData.add(VideoAttr.fromJson({
              'title': video['flag'],
              'index': i,
              'list': video['video'].map((item){
                List<String> videoList = item.split('\$');
                return {
                  'title': videoList[0],
                  'index': i,
                  'url': videoList.length >= 2 ? videoList[1] : '',
                };
              }).toList()
            }));
          }

          setState(() {
            currentData = detailData[0].list[0];
            title = value['title'];
          });
        }
      }
    });
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      body: Stack(
        children: [
          Positioned(
            top: MediaQuery.of(context).padding.top,
            left: 0,
            right: 0,
            height: ScreenUtil.getInstance().getSp(260),
            child: Container(
              alignment: Alignment.center,
              color: Colors.black,
              child: VideoPlayPage(title: title ?? '', url: currentData?.url ?? '')
            ),
          ),
          Positioned(
            top: MediaQuery.of(context).padding.top + ScreenUtil.getInstance().getSp(260),
            left: 0,
            bottom: 0,
            right: 0,
            child: Container(
              color: Colors.grey[200],
              child: Column(
                children: detailData.map((item){
                  return titleItem(left: "来源(${item.title})", right: "${item.index == currentData?.index ? currentData?.title ?? '' : ''}", leftIcon: Icons.filter_list, rightSize: 10, rightIcon: Icons.arrow_forward_ios, index: 2, data: item.list);
                }).toList(),
              )
            )
          ),
        ],
      ),
    );
  }

  Widget titleItem({String left, String right, IconData leftIcon, IconData rightIcon, double rightSize = 15, Color rightColor = Colors.grey, int index = 0, List<VideoAttr> data }) {
    if(data == null) return Container();
    return InkWell(
      child: Container(
        padding: EdgeInsets.only(
          top: 15,
          left: 10,
          right: 10
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                Icon(
                  leftIcon
                ),
                Text(
                  '$left',
                  style: TextStyle(
                    fontSize: 15 
                  ),
                ),
              ],
            ),
            Row(
              children: <Widget>[
                right != null && right.isNotEmpty ? Text(
                  '$right',
                  style: TextStyle(
                    fontSize: rightSize,
                    color: rightColor
                  ),
                ) : Container(),
                rightIcon != null && rightIcon is IconData ? Icon(
                  rightIcon,
                  size: 16,
                ) : Container(),
              ],
            )
          ],
        ),
      ),
      onTap: () {
        if( index == 2 ){
          showBottomSheet(data);
        }
      },
    );
  }

  void showBottomSheet( List<VideoAttr> data ){
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
          side: BorderSide(
          color: Color(0xFFF9F3FF), 
          style: BorderStyle.solid, width: 2
        )
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder:(stateContext, state) {
            return SafeArea(
            child: Container(
              padding: EdgeInsets.symmetric(
                horizontal: ScreenUtil.getInstance().getWidth(10)
              ),
              child: 
              // Wrap(
              //   spacing: 5,
              //   runSpacing: 5,
              //   children: data.map((item){
              //     return OutlineButton(
              //       onPressed: () async {
              //         print('源');
              //         setState(() {
              //           playCurrentUrl = item.url;
              //         });
              //         Navigator.of(context).pop();
              //       },
              //       shape: RoundedRectangleBorder(
              //         borderRadius: BorderRadius.all( Radius.circular(6) ),
              //       ),
              //       borderSide: BorderSide(
              //         color: playCurrentUrl == item.url ? Theme.of(context).primaryColor : Colors.grey,
              //         style: BorderStyle.solid, 
              //         width: 1
              //       ),
              //       child: Text(
              //         '${item.title}',
              //         textAlign: TextAlign.center,
              //         overflow: TextOverflow.ellipsis,
              //       ),
              //     ); 
              //   }).toList(),
              // ),
              GridView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.only(
                  top: 10,
                  bottom: 5,
                  left: 1,
                  right: 1,
                ),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  childAspectRatio: 2.2,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                ),
                // physics: NeverScrollableScrollPhysics(),
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index){
                  return OutlineButton(
                    padding: EdgeInsets.symmetric(
                      horizontal: 2
                    ),
                    onPressed: () async {
                      print('源${index+1}');
                      setState(() {
                        currentData = data[index];
                      });
                      Navigator.of(context).pop();
                    },
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all( Radius.circular(6) ),
                    ),
                    borderSide: BorderSide(
                      color: currentData.url == data[index].url ? Theme.of(context).primaryColor : Colors.grey,
                      style: BorderStyle.solid, 
                      width: 1
                    ),
                    child: Text(
                      '${formVideoData[index].title}',
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.clip,
                      maxLines: 1,
                      style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.normal
                      ),
                    ),
                  );
                },
              ),
            ),
          );
        });
      },
    );
  }

}
